package cn.lxh.template;

import cn.lxh.properties.OssProperties;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author lxh Create Time: 2023/12/30 13:06
 * OSS对象存储工具类
 */
public class OssTemplate {

    private OssProperties ossProperties;

    public OssTemplate(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }

    // 文件上传
    public String upload(String fileName, File file) {
        // 地域端点
        String endpoint = ossProperties.getEndpoint();
        // key和密钥
        String accessKeyId = ossProperties.getAccessKeyId();
        String accessKeySecret = ossProperties.getAccessKeySecret();
        // 桶名
        String bucketName = ossProperties.getBucketName();

        // 创建ossClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象 (如果不传file, 可以穿输入流)
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file);

        // 上传文件
        ossClient.putObject(putObjectRequest);

        // 关闭ossClient
        ossClient.shutdown();

        // 图片云端地址
        // https://%s.oss-cn-chengdu.aliyuncs.com/%s -> https://fccar0820.oss-cn-chengdu.aliyuncs.com/1740958723507097600.png
        String ossPath = String.format(ossProperties.getOssPath(), bucketName, fileName);
        // 返回图片云端地址
        return ossPath;
    }


    // 将MultipartFile类型转换为File类型
    public File transferToFile(MultipartFile multipartFile) {
        // 选择用缓冲区来实现这个转换即使用java创建的临时文件, 使用MultipartFile.transferto()方法
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file = File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

}
